package com.shaoshaohuo.app.ui;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Application;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.ViewParent;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.SshApplication;
import com.shaoshaohuo.app.db.DaoUtils;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.UserInfoEntity;
import com.shaoshaohuo.app.entity.VersionInfoEntity;
import com.shaoshaohuo.app.entity.VersionInfoEntity.VersionInfo;
import com.shaoshaohuo.app.framework.AccountManager;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper.Field;
import com.shaoshaohuo.app.net.HttpConfig;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.utils.DeviceHelper;
import com.shaoshaohuo.app.utils.Location2Util;
import com.shaoshaohuo.app.utils.StringUtil;
import com.shaoshaohuo.app.utils.im.IMFactory;
import com.umeng.analytics.MobclickAgent;

import java.util.List;

import cn.jpush.android.api.JPushInterface;

public class WelcomeActivity extends BaseActivity {
    private static final int WRITE_EXTERNAL_STORAGE_REQUEST_CODE = 11;
    private static final int ACCESS_FINE_LOCATION_REQUEST_CODE = 12;
    // 网络框架没有取消机制，为了避免 超时 引起 弹框稍后 ，超时后 置为true 不弹框
    private static boolean isFinish = false;

    private int screenWidth;
    private int screenHeight;

    private final static double IMAGE_WIDTH = 640.00;
    private final static double IMAGE_HEIGHT = 1136.00;

    private ImageView imageview;
    private Handler handler;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_welcome);

        getScreenWidth();

        initLayout();

//		parent.
//
        checkVersion();

        checkServerNameIsChanged();

        rquestStoragePermission();

    }

    private void rquestStoragePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                    WRITE_EXTERNAL_STORAGE_REQUEST_CODE);
        } else {
            if (DeviceHelper.getVersionCode(this) > SharedPreferencesHelper.getInt(Field.DB_VERSION, -1)) {
                DaoUtils.init();
                SharedPreferencesHelper.setInt(Field.DB_VERSION, DeviceHelper.getVersionCode(this));
            }
            DaoUtils.initDaoConfig();
            requestLocationPermission();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case WRITE_EXTERNAL_STORAGE_REQUEST_CODE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // Permission Granted
                    DaoUtils.init();
                    DaoUtils.initDaoConfig();
                    requestLocationPermission();
                } else {
                    // Permission Denied
                }
                break;
            case ACCESS_FINE_LOCATION_REQUEST_CODE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Location2Util.getInstance(SshApplication.getContext()).startLocation();
                    handler = new Handler();
                    handler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            isFinish = true;
                            next();
                        }
                    }, 1500);
                }
            default:
                break;
        }
    }

    private void requestLocationPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) {
            //申请WRITE_EXTERNAL_STORAGE权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    ACCESS_FINE_LOCATION_REQUEST_CODE);
        } else {
            Location2Util.getInstance(SshApplication.getContext()).startLocation();
            handler = new Handler();
            handler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    isFinish = true;
                    next();
                }
            }, 1500);
        }
    }

    /**
     * 判断服务器域名是否变化。如果有变化，清空用户session
     */
    private void checkServerNameIsChanged() {
        String lastedServerName = SharedPreferencesHelper.getString(Field.LATEST_SERVER_NAME, "");
        if (!StringUtil.isEmpty(lastedServerName)) {
            if (!HttpConfig.BASE_HOST_URL.equals(lastedServerName)) {
                AccountManager.logout(this);
                SharedPreferencesHelper.setString(Field.LATEST_SERVER_NAME, HttpConfig.BASE_HOST_URL);
            }
        } else {
            AccountManager.logout(this);
            SharedPreferencesHelper.setString(Field.LATEST_SERVER_NAME, HttpConfig.BASE_HOST_URL);
        }
    }

    private void checkVersion() {
        String versionName = DeviceHelper.getVersionName(this);
        final int ignoreVersionId = SharedPreferencesHelper.getInt(Field.IGNORE_VERSION_ID, 0);
        // 接口
        RequestService.getInstance().checkVersion(this, versionName, VersionInfoEntity.class, new RequestListener() {
            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                if (resultData.isOk()) {
                    VersionInfoEntity entity = (VersionInfoEntity) resultData;
                    List<VersionInfo> list = entity.data.list;
                    if (list != null && list.size() > 0) {
                        if (ignoreVersionId < Integer.parseInt(list.get(list.size() - 1).id)) {
                            if (!isFinish) {
                                showNewVersion(entity.data.list);
                            }
                        }
                    }
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {

            }
        });

    }

    private void showNewVersion(List<VersionInfo> list) {
        handler.removeCallbacksAndMessages(null);
        final VersionInfo currentVersion = list.get(list.size() - 1);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("有新版本");
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = list.size() - 1; i >= 0; i--) {
            VersionInfo info = list.get(i);
            stringBuilder.append(info.version);
            stringBuilder.append("	");
            stringBuilder.append(info.cdate.split(" ")[0]);
            stringBuilder.append("\n");
            stringBuilder.append("更新内容：" + info.content);
            stringBuilder.append("\n");
        }
        builder.setMessage(new String(stringBuilder));
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Uri uri = Uri.parse(HttpConfig.WebPage.DOWNLOAD_APP);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
                finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                SharedPreferencesHelper.setInt(Field.IGNORE_VERSION_ID, Integer.parseInt(currentVersion.id));
                next();
            }
        });
        builder.setCancelable(false);
        builder.create().show();
    }

    private void initLayout() {
        imageview = (ImageView) this.findViewById(R.id.imageview_welcome);
        changeTransltestaus(imageview, this, TransltestausModel.TOPPicter, -1);
//        double d1 = (double) IMAGE_WIDTH / (double) IMAGE_HEIGHT;
//        double d2 = (double) screenWidth / (double) screenHeight;
////		Log.d(TAG, "initLayout: ");
//        if (d1 > d2) {
//            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageview.getLayoutParams();
//            params.height = screenHeight;
//            params.width = (int) ((double) IMAGE_WIDTH * ((double) screenHeight / IMAGE_HEIGHT));
//            int m = (int) ((double) ((double) IMAGE_WIDTH * ((double) screenHeight / IMAGE_HEIGHT)) - screenWidth) / 2;
//            params.leftMargin = -m;
//            params.rightMargin = -m;
//            imageview.setLayoutParams(params);
//        } else if (d2 > d1) {
//            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) imageview.getLayoutParams();
//            params.width = screenWidth;
////			params.height = (int) ((double) IMAGE_HEIGHT * ((double) screenWidth / IMAGE_WIDTH));
//            params.height = screenHeight;
//            int m = (int) ((double) ((double) IMAGE_HEIGHT * ((double) screenWidth / IMAGE_WIDTH)) - screenHeight) / 2;
//            params.topMargin = -m;
//            params.bottomMargin = -m;
//            imageview.setLayoutParams(params);
//        }

    }

    private void getScreenWidth() {
        screenWidth = DeviceHelper.getScreenWidth(this);
        screenHeight = DeviceHelper.getScreenHeight(this);
    }

    private void next() {

        // 第一次安装，显示引导页面
        int currentVersionCode = SharedPreferencesHelper.getInt(Field.CODE_VERSION, -1);
        PackageManager pm = getPackageManager();
        Application app = getApplication();
        PackageInfo pi = null;
        Intent intent = null;
        try {
            pi = pm.getPackageInfo(app.getPackageName(), 0);
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        if (pi != null && pi.versionCode != currentVersionCode) {
            intent = new Intent(WelcomeActivity.this, SplashActivity.class);
        } else {
            if (AccountManager.isLogin()) {
                // 登录IM
                loginIm();
                MobclickAgent.onProfileSignIn(AccountManager.getUserId());
                // 显示 角色 选择页面
                int defaultDisplay = SharedPreferencesHelper.getInt(Field.DEFAULT_DISPLAY, 0);
                switch (defaultDisplay) {
                    case 0:
                        intent = new Intent(WelcomeActivity.this, SelectDisplayActivity.class);
                        break;
                    case 1:
                        intent = new Intent(WelcomeActivity.this, MainTabActivity.class);
                        SshApplication.main_state = 1;
                        break;
                    case 2:
                        intent = new Intent(WelcomeActivity.this, MainTabActivity.class);
                        SshApplication.main_state = 2;
                        break;
                }
            } else {
                intent = new Intent(WelcomeActivity.this, LoginActivity.class);
            }
        }
        startActivity(intent);
        finish();
    }


    /**
     *
     */
    private void loginIm() {
        RequestService.getInstance().getUserInfo(this, UserInfoEntity.class, new RequestListener() {

            @Override
            public void onSuccess(int requestCode, BaseEntity resultData) {
                if (resultData.isOk()) {
                    UserInfoEntity entity = (UserInfoEntity) resultData;
                    AccountManager.saveUserInfo(entity.getData());
                    // 登录IM
                    IMFactory.login(IMFactory.getImId(entity.getData().getUserid()), IMFactory.default_password, null);
                } else {
//                    showToast(resultData.getMsg());
                }
            }

            @Override
            public void onFailed(int requestCode, Exception error, String msg) {
//                showToast(R.string.please_check_network);
            }
        });
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.anim_right_in, R.anim.anim_left_out);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onPause() {
        JPushInterface.onPause(this);
        MobclickAgent.onPageEnd("WelcomeActivity");
        MobclickAgent.onPause(this);
        super.onPause();
    }

    @Override
    protected void onResume() {
        JPushInterface.onResume(this);
        MobclickAgent.onPageStart("WelcomeActivity");
        MobclickAgent.onResume(this);
        super.onResume();
    }

}
